package com.huanxing.cloud.security.config;

import cn.hutool.core.util.StrUtil;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.common.core.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * 自定义认证异常处理
 *
 * @author lijx
 * @date 2022/5/15 18:08
 * @version 1.0
 */
@Slf4j
@Component
public class HxAuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
  @Override
  public void commence(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException authException)
      throws IOException {
    int code = HttpStatus.UNAUTHORIZED.value();
    String msg = StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
    log.error(msg);
    response.setStatus(code);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setCharacterEncoding("utf-8");
    PrintWriter writer = response.getWriter();
    Result<String> result = new Result();
    result.setCode(CommonConstants.FAIL);
    result.setMsg(msg);
    writer.print(result);
  }
}
